//
//  SWScanTextViewController.m
//  DataTransfer
//
//  Created by 宋润理 on 2023/12/21.
//  Copyright © 2023 James. All rights reserved.
//

#import "SWScanTextViewController.h"
#import "SWWebViewViewController.h"

@import Vision;
@import VisionKit;

@interface SWScanTextViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate,VNDocumentCameraViewControllerDelegate>
@property (nonatomic, strong) UIButton *selectImageBtn;
@property (nonatomic, strong) UIButton *cameraBtn;
@property (nonatomic, strong) UITextView *resultView;

@end

@implementation SWScanTextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"扫描序列号";
    [self setLeftItemWithIcon:[UIImage imageNamed:@"back"] title:nil selector:@selector(onClickBack)];
    [self setRightItemWithTitle:@"查询" selector:@selector(jumpWeb) color:MainThemeColor];

    [self.view addSubview:self.selectImageBtn];
    [_selectImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(25));
        make.right.equalTo(@(-25));
        make.bottom.equalTo(@(-100));
        make.height.equalTo(@(50));
    }];
    
    [self.view addSubview:self.cameraBtn];
    [_cameraBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(self.selectImageBtn);
        make.bottom.equalTo(self.selectImageBtn.mas_top).offset(-25);
    }];
    
    UIImageView *mainImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Apple1024"]];
    mainImage.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:mainImage];
    [mainImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(25));
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.height.equalTo(@(100));
    }];
    
    [self.view addSubview:self.resultView];
    self.resultView.text = @"请扫描包装上的序列号或拍照扫描照片……";
    [_resultView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.cameraBtn);
        make.top.equalTo(mainImage.mas_bottom).offset(25);
        make.bottom.equalTo(self.cameraBtn.mas_top).offset(-100);
    }];
}

- (void)onClickBack {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)onClickSelectImage:(UIButton *)btn
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)onClickCameraBtn{
    VNDocumentCameraViewController *vc = [[VNDocumentCameraViewController alloc] init];
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:nil];

}

- (void)jumpWeb {
    
    SWWebViewViewController *vc = [[SWWebViewViewController alloc] initWithUrl:@"https://checkcoverage.apple.com/"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)performTextRecognitionOnImage:(UIImage *)image {
    if (image == nil) {
        return;
    }
    
    VNRecognizeTextRequest *request = [[VNRecognizeTextRequest alloc] initWithCompletionHandler:^(VNRequest * _Nonnull request, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error: %@", error);
            return;
        }
        
        NSArray<VNRecognizedTextObservation *> *observations = request.results;
        if (observations.count > 0) {
            NSMutableString *detectedText = [NSMutableString string];
            for (VNRecognizedTextObservation *observation in observations) {
                VNRecognizedText *topCandidate = [observation topCandidates:1].firstObject;
                [detectedText appendString:topCandidate.string];
                [detectedText appendString:@"\n"];
            }

            self.resultView.text = detectedText;
        }else{
            self.resultView.text = @"无法识别图像中的文字。";
        }
    }];
    request.recognitionLevel = VNRequestTextRecognitionLevelAccurate; // 采用精确路径
    request.recognitionLanguages = @[@"zh-Hans", @"en-US"]; // 设置识别的语言
    
    VNImageRequestHandler *handler = [[VNImageRequestHandler alloc] initWithCGImage:image.CGImage options:@{}];
    
    NSError *error;
    [handler performRequests:@[request] error:&error];
    
    if (error) {
        NSLog(@"Error: %@", error);
    }
}

#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * image = info[@"UIImagePickerControllerOriginalImage"];
    
    [self performTextRecognitionOnImage:image];
}


- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller didFinishWithScan:(VNDocumentCameraScan *)scan{
    for (int i = 0; i < scan.pageCount; i++) {
        [self performTextRecognitionOnImage:[scan imageOfPageAtIndex:i]];
    }
    [controller dismissViewControllerAnimated:YES completion:nil];
}


- (void)documentCameraViewControllerDidCancel:(VNDocumentCameraViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];

}

- (void)documentCameraViewController:(VNDocumentCameraViewController *)controller didFailWithError:(NSError *)error{
    [controller dismissViewControllerAnimated:YES completion:nil];

}
#pragma mark - getter
- (UIButton *)selectImageBtn{
    if(!_selectImageBtn){
        _selectImageBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_selectImageBtn setTitle:@"扫描图片" forState:UIControlStateNormal];
        [_selectImageBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _selectImageBtn.layer.cornerRadius = 10;
        _selectImageBtn.layer.masksToBounds = YES;
        _selectImageBtn.backgroundColor = MainThemeColor;
        [_selectImageBtn addTarget:self action:@selector(onClickSelectImage:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectImageBtn;
}

- (UIButton *)cameraBtn{
    if(!_cameraBtn){
        _cameraBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_cameraBtn setTitle:@"拍照扫描" forState:UIControlStateNormal];
        [_cameraBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _cameraBtn.layer.cornerRadius = 10;
        _cameraBtn.layer.masksToBounds = YES;
        _cameraBtn.backgroundColor = MainThemeColor;
        [_cameraBtn addTarget:self action:@selector(onClickCameraBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cameraBtn;
}
- (UITextView *)resultView{
    if(!_resultView){
        _resultView = [[UITextView alloc] init];
        _resultView.font = [UIFont systemFontOfSize:14];
        _resultView.textColor = MainThemeColor;
        _resultView.backgroundColor = UIColor.whiteColor;
        _resultView.editable = NO;
    }
    return _resultView;
}
@end
